import React, { Component } from 'react'
import { Row, Col, Radio, DatePicker, Switch, InputNumber, Button, message } from 'antd';
import moment from 'moment';
import Modal from '../../../components/Modal/index';
import services from '../../../services/api';
moment.locale('zh-cn');

export default class Publish extends Component{
  constructor(props){
    super(props)
    this.state = {
      type: 1,
      effective_time: '',
      isGray: true,
      sample_rate: 99,
    }
    this.record = props.record
    this.publishType = props.type // 'publish': 发布; 'reissue'：重新发布
  }

  componentDidMount(){
    if (this.publishType === 'reissue') { // 是否是重新发布
      this.setState({
        isGray: this.record.sample_rate ? true : false,
        sample_rate: this.record.sample_rate === 100 ? 99 : (this.record.sample_rate || 99)
      })
    }
  }

  // 发布前判断是否有在线版本
  publisConfirm = () => {
    const { isGray, sample_rate, type, effective_time } = this.state
    if (type === 2 && !effective_time) return message.warn('请选择发布时间')
    if (isGray) {
      if (!sample_rate) {
        return message.warning('请输入灰度占比')
      }
      services.produce.getPublishStrategy({ strategy_id: this.record.strategy_id }).then(res => {
        if (res.code === 0) {
          if (res.data.msg) {
            this.openConfirm(res.data.msg)
          } else {
            this.publish()
          }
        } else {
          message.error(res.msg)
        }
      })
    } else {
      this.publish()
    }
  }

  openConfirm(msg) {
    Modal.open({
      title: '',
      width: '360px',
      isConfirm: true,
      content: <p>{msg}</p>,
      isOkBtn: true,
      isCancelBtn: true,
      ok: () => {
        this.publish()
      },
      cancel: () => {
        Modal.close();
      },
    });
  }

  publish = () => {
    const { type, effective_time, isGray, sample_rate } = this.state
    let params = {
      strategy_id: this.record.strategy_id,
      sample_rate: isGray ? (sample_rate || 99) : '',
      effective_time: type === 2 ? effective_time : ''
    }
    services[this.publishType === 'publish' ? 'strategyFlow' : 'produce'].publish(params).then(res => {
      if (res.code === 0) {
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
      this.props.closeModel();
    })
  }

  render() {
    const { type, isGray, sample_rate, effective_time } = this.state
    return (
      <div style={{ margin: '0 30px' }}>
        <Row style={{ marginBottom: 20 }}>
          <Col span={5}>发布方式:</Col>
          <Col>
            <Radio.Group onChange={(e) => this.setState({ type: e.target.value })} value={type}>
              <Radio value={1}>立即发布</Radio>
              <Radio value={2} disabled={this.publishType === 'reissue'}>定时发布</Radio>
            </Radio.Group>
            {type === 2 && <DatePicker
              showTime={true}
              format='YYYY-MM-DD HH:mm:ss'
              onChange={(date, dateString) => this.setState({ effective_time: dateString})}
              value={effective_time ? moment(effective_time) : undefined}
              disabledDate={(current) => current < moment(new Date())}
            />}
          </Col>
        </Row>
        <Row style={{ marginBottom: 20 }}>
          <Col span={5}>灰度发布:</Col>
          <Col>
            <Switch onChange={(value) => this.setState({ isGray: value })} checked={isGray}></Switch>
          </Col>
        </Row>
        {isGray && <Row style={{ marginBottom: 20 }}>
          <Col span={5}>灰度流量占比:</Col>
          <Col>
            <InputNumber size="small" min={1} max={99} defaultValue={1} onChange={(value) => this.setState({ sample_rate: value })} value={sample_rate} />
            <span>（灰度流量1%~99%）</span>
          </Col>
        </Row>}
        <Row style={{ marginBottom: 20 }} type='flex' justify='center'>
          <Button type='primary' autoFocus={true} onClick={this.publisConfirm}>确定</Button>
          <Button style={{ marginLeft: 20 }} onClick={this.props.closeModel}>取消</Button>
        </Row>
      </div>
    )
  }
}